package com.fq.wechat.controller;

import com.fq.wechat.constant.CommonConstant;
import com.fq.wechat.domain.SensorDO;
import com.fq.wechat.domain.SensorVO;
import com.fq.wechat.service.CC3200Service;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jifang.
 * @since 2016/4/3 11:40.
 */

@Controller
@RequestMapping("/cc3200")
public class CC3200Controller {

    private Logger LOGGER = LoggerFactory.getLogger(CC3200Controller.class);

    @Autowired
    private CC3200Service cService;

    private static final String formatter = "light=%s,fan=%s";

    @RequestMapping(value = "/upload_and_get.do", method = {RequestMethod.POST, RequestMethod.GET})
    public void uploadAndGet(SensorVO input, HttpServletRequest request, HttpServletResponse response) throws IOException {
        SensorDO sensor = new SensorDO();
        String light = input.getLight();
        if (!Strings.isNullOrEmpty(light)) {
            sensor.setLight(light);
        }
        sensor.setTemperature(input.getTemperature());
        sensor.setHumidity(input.getHumidity());
        // 保存温度/湿度信息
        cService.saveSensor(sensor, input.getSequence());

        // 获得光照/风扇状态
        sensor = cService.getSensor(input.getSequence());
        if (sensor == null) {
            sensor = new SensorDO();
            sensor.setLight(CommonConstant.OFF);
            sensor.setFan(CommonConstant.OFF);
        }
        String result = String.format(formatter, sensor.getLight(), sensor.getFan());
        response.getWriter().print(result);
    }
}
